﻿var gadgetWindow = System.Gadget.document.parentWindow;

function getTeamLogo(team) {
    if (team.LogoUri == null)
        return "";

    var logoUrl = gadgetWindow.interop.UriToString(team.LogoUri);
    gadgetWindow.msgbox(logoUrl);
    return "<img src='" + logoUrl + "' width='24' height='24' />";
}

function addTeamColumn(row, content, title) {
    var cell = row.insertCell(-1);
    cell.innerHTML = content;
    cell.title = title;
    return cell;
}

function addTeamNameColumn(row, team) {
    addTeamColumn(row, "<span>" + getTeamLogo(team) + " " + team.Name + "</span>", "");
}

function addTeam(index, team) {    
    var table = document.getElementById("leagueGrid").tBodies[0];
    var row = table.insertRow(-1);
    if (team == null)
        return true;

    row.id = team.ID;

    addTeamColumn(row, team.LeagueStats.Position, "");
    addTeamColumn(row, "-", "");
    addTeamColumn(row, team.Name, "");
    addTeamColumn(row, team.LeagueStats.PlayedMatches);
    addTeamColumn(row, team.LeagueStats.Wins, "");
    addTeamColumn(row, team.LeagueStats.Draws, "");
    addTeamColumn(row, team.LeagueStats.Losses, "");
    addTeamColumn(row, team.LeagueStats.GoalsFor, "");
    addTeamColumn(row, team.LeagueStats.GoalsAgainst, "");
    addTeamColumn(row, team.LeagueStats.HomeWins, "");
    addTeamColumn(row, team.LeagueStats.HomeDraws, "");
    addTeamColumn(row, team.LeagueStats.HomeLosses, "");
    addTeamColumn(row, team.LeagueStats.HomeGoalsFor, "");
    addTeamColumn(row, team.LeagueStats.HomeGoalsAgainst, "");
    addTeamColumn(row, team.LeagueStats.AwayWins, "");
    addTeamColumn(row, team.LeagueStats.AwayDraws, "");
    addTeamColumn(row, team.LeagueStats.AwayLosses, "");
    addTeamColumn(row, team.LeagueStats.AwayGoalsFor, "");
    addTeamColumn(row, team.LeagueStats.AwayGoalsAgainst, "");
    addTeamColumn(row, team.LeagueStats.GoalsFor - team.LeagueStats.GoalsAgainst);
    addTeamColumn(row, team.LeagueStats.Points);            
}

function updateLeagueGrid() {
    var teams = gadgetWindow.interop.ToArray(gadgetWindow.MyTeam.League.TeamsByPosition);
    $.each(teams, addTeam);

    $("#" + gadgetWindow.MyTeam.ID).addClass("userTeam");
}

function enableSorting() {
    $("#leagueGrid").tablesorter();
}

function showError(msg) {
    $("body").prepend("<span>" + msg + "</span>").css("color", "red");
}

$(document).ready(function() {

    if (!gadgetWindow) {
        showError("Sdad");
        return;
    }
    
    updateLeagueGrid();
    enableSorting();
});